/* jshint esversion: 11 */
import { debounce } from './utils/debounce.js';

window.addEventListener('load', async () => {
    let config = null;
    const initHrefList = (await window.btnList).map((item) => {
        if (item.href[0] == '.') return item.href.slice(2);
        else return item.href;
    });
    (function readConfig() {
        config = localStorage.path_resolver;
        if (!config)
            config = {
                showFormatType: 0
            };
        else config = JSON.parse(config);
    })();
    window.saveConfig = function (_config) {
        if (_config) {
            config = _config;
        }
        localStorage.path_resolver = JSON.stringify(config);
    };

    let parseHTML = import('./parse-directory.js') // 也可以换到utils里
        .then((module) => (parseHTML = module.parseHTML)); // 不过写作函数导入示例吧

    const path = document.getElementById('resolve'),
        pathList = document.getElementById('pathList');
    let hrefList, pointer;
    let updateHrefList = null;

    switch (config.showFormatType) {
        case 2:
            updateHrefList = function () {
                console.clear();
                if (!hrefList || hrefList.length == 0) return;
                let before = new Array(hrefList.length - 1 - pointer);
                console.log(before.concat(hrefList.slice(0, pointer), ['']).join('\n'));
                if (hrefList[pointer]) console.warn(hrefList[pointer]);
                console.log(hrefList.slice(pointer + 1).join('\n'));
            };
            break;
        case 1:
            updateHrefList = function () {
                console.clear();
                if (!hrefList || hrefList.length == 0) return;
                let before = new Array(hrefList.length - 1 - pointer);
                console.log(before.concat(hrefList.slice(0, pointer), ['']).join('\n'));
                if (hrefList[pointer]) console.warn(hrefList[pointer]);
                console.log(hrefList.slice(pointer + 1).join('\n'));
            };
            break;
        case 0:
        default:
            let pathElemList = [],
                lastActive = null;
            updateHrefList = function (isRefresh = true) {
                if (isRefresh) {
                    pathElemList = [];
                    pathList.innerHTML = '';
                    pointer = 0;
                    hrefList.forEach((_path, _index) => {
                        let _li = document.createElement('li');
                        _li.textContent = _path;
                        pathList.append(_li);
                        pathElemList.push(_li);
                    });
                }
                lastActive && lastActive.classList.remove('active');
                (lastActive = pathElemList[pointer]).classList.add('active');
            };
    }

    function resolve(ev) {
        pointer = 0;
        if (path.value == './') {
            hrefList = initHrefList;
            updateHrefList();
        } else {
            hrefList = fetch(path.value)
                .then(
                    (e) => e.text(),
                    (err) => 0
                )
                .then(
                    async (html) => {
                        await parseHTML;
                        hrefList = parseHTML(html);
                        hrefList = hrefList.map((v) => v.slice(location.href.length));
                        updateHrefList();
                    },
                    (err) => 0
                );
        }
    }
    let debounce_resolve = debounce(resolve, 100);
    path.addEventListener('input', () => {
        let _url = path.value;
        if (_url[_url.length - 1] == '/') debounce_resolve();
    });
    path.addEventListener('keydown', async (ev) => {
        await hrefList;
        let url = path.value;
        if (['ArrowDown', 'ArrowUp'].includes(ev.key)) {
            ev.preventDefault();
            if (ev.key === 'ArrowDown') {
                pointer++;
            } else if (ev.key == 'ArrowUp') {
                pointer--;
            }
            pointer = (pointer + hrefList.length) % hrefList.length;
            updateHrefList(false);
            return;
        } else if (ev.key === 'Tab') {
            ev.preventDefault();
            if (ev.shiftKey) {
                let last = url.slice(0, url.length - 1).lastIndexOf('/');
                path.value = url.slice(0, last + 1);
            } else if (hrefList.length) {
                if (hrefList[pointer].startsWith('http')) {
                    path.value = hrefList[pointer];
                } else {
                    path.value += hrefList[pointer];
                }
            }
            debounce_resolve();
        } else if (ev.key === 'Enter') {
            ev.preventDefault();
            window.open(url);
        }
    });
    resolve(path.value);
});
